﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using NLog;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace DDASProject.CEUtility
{
    public partial class BaseForm : Form
    {   
#region 属性与变量

        protected string _userID; //用户工号
        protected string _userGroup; //用户部门
        protected SqlCeConnection _sqlceConn; //SQLCE数据库
        protected string _sqlCEConnStr; //Sqlce连接字符串
        protected WebService.BarCodeService _svr; //webservice
        protected string _myAppName;  //程序名        
        protected AppID _myAppID;   //程序ID
        protected Logger _logger;  //日志记录器
        protected bool _isEndproductBarcode; //是否成品条码
        protected DataTable _dtSource; //datatable
        private static Dictionary<AppID,int> _hasUpdateChecked; //已检测过更新的程序 
        private const  int _maxCheckCount  = 10; //每打开多少次检测一次版本
        public System.Data.DataTable DTSource
        {
            get { return _dtSource; }
            set { _dtSource = value; }
        }
        public string UserID
        {
            get { return _userID; }            
        }
        public string UserGroup
        {
            get { return _userGroup; }            
        }
        public System.Data.SqlServerCe.SqlCeConnection SqlceConn
        {
            get { return _sqlceConn; }
            set { _sqlceConn = value; }
        }
        public WebService.BarCodeService WebSvr
        {
            get { return GetWebService(); }            
        }
        public DDASProject.CEUtility.AppID MyAppID
        {
            get { return _myAppID; }            
        }
        public string MyAppName
        {
            get { return _myAppID.ToString(); }            
        }
        public Logger Logger
        {
            get { return _logger; }            
        }
#endregion

        static BaseForm()
        {
            _hasUpdateChecked = new Dictionary<AppID, int>();            
        }
        public BaseForm():this(AppID.Unknow,string.Empty,string.Empty)
        {

        }
        public BaseForm(AppID appID) : this(appID, string.Empty, string.Empty)
        {          
        }
        public BaseForm(AppID appID, string userID, string userGroup)
        {
            this._userID = userID;
            this._userGroup = userGroup;
            this._myAppID = (AppID)appID;
            this._logger = Common.Logger;
            this._svr = null;
            this._isEndproductBarcode = false; //默认效验条码为材料条码
            this._dtSource = null;
            this._sqlCEConnStr = "Data Source="+Common.ApplicationPath + "\\DBCache.sdf;"+"Password=gzelite";
            base.Size = new Size(240, 300);
            InitializeComponent();
        }

        public virtual void InitSqlCEConnection()
        {
            if (string.IsNullOrEmpty(_sqlCEConnStr))
            {
                throw new ArgumentNullException("连接字符串不能为空");
            }
            
            try
            {
                _sqlceConn = new SqlCeConnection(_sqlCEConnStr);              
            }
            catch (System.Exception ex)
            {            	
            	throw ex;            	
            }
        }

        /// <summary>
        /// 获取WebService对象
        /// </summary>
        /// <returns></returns>
        public virtual WebService.BarCodeService GetWebService()
        {  
            try
            {
                //优先使用独立设置,其次使用公共设置
                string url = string.Empty;
                url = Common.GetAppSetting(_myAppID.ToString(), "Url");
                if (string.IsNullOrEmpty(url))
                {
                    url = Common.GetGlobalSetting("DefaultUrl");
                }
                if (_svr != null && !string.IsNullOrEmpty(url))
                {
                    _svr.Url = url;
                    return _svr;
                }                
                _svr = new WebService.BarCodeService();
                _svr.Url = url;
            }
            catch (System.Exception ex)
            {
            	Common.Logger.Error(ex);
            	throw ex;
            	
            }
            return _svr;

        }

        /// <summary>
        /// 模块名
        /// </summary>
        /// <returns></returns>
        public virtual string GetMyAppName()
        {
            return MyAppName;
        }

        /// <summary>
        /// 材料条码效验
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        protected virtual bool BarcodeVaild(string barcode,decimal totalQuantity)
        {
            return BarcodeVaild(0, barcode,totalQuantity);
        }
       /// <summary>
       /// 条码验证
       /// </summary>
        /// <param name="barCodeType">条码类型 0:成品,1:材料,2电解纸</param>
       /// <param name="barcode"></param>
       /// <returns></returns>
        protected virtual bool BarcodeVaild(int barCodeType, string barcode, decimal totalQuantity)
        {
            if (string.IsNullOrEmpty(barcode))
            {
                MessageBox.Show("条码不能为空");
                return false;
            }
            bool bRet = false;
            try
            {
                int nRet = WebSvr.BarcodeVaild(barCodeType, barcode, totalQuantity);
                if (nRet == 0)
                {
                    bRet = true;
                }
                else
                {
                    Common.PlayWarning();
                    MessageBox.Show(Error.GetErrorMsg((ErrorCode)nRet), "错误");
                    bRet = false;                   
                }
            }
            catch (System.Exception ex)
            {
                Common.PlayWarning();
                Logger.Error(ex);
            	MessageBox.Show(ex.Message);
            }
            return bRet;
        }

        /// <summary>
        /// 仓库验证
        /// </summary>
        /// <param name="depotID"></param>
        /// <returns></returns>
        protected virtual bool DepotVaild(string depotID)
        {
            if (string.IsNullOrEmpty(depotID) )
            {
                return false;
            }
            bool bRet = false;
            try
            {
                if (null == _sqlceConn)
                {
                    InitSqlCEConnection();
                }
                string sql = "select count(*) from t_Depot where depotID=@depotID";
                SqlCeParameter p1 = new SqlCeParameter("@depotID", SqlDbType.NVarChar, 20);
                p1.Value = depotID;
                object objRet = SqlCeHelper.ExecuteScalar(_sqlceConn, sql, p1);
                if (null != objRet && Convert.ToInt32(objRet) > 0)
                {
                    bRet = true;
                }
                else
                {
                    Common.PlayWarning();
                    bRet = false;
                }
            }
            catch (System.Exception ex)
            {
            	Logger.Error(ex);
            	MessageBox.Show(ex.Message);            	
            }
            return bRet;
        }

        /// <summary>
        /// 储位验证
        /// </summary>
        /// <param name="locID"></param>
        /// <returns></returns>
        protected virtual bool LocVaild(string locID)
        {
            if (string.IsNullOrEmpty(locID))
            {
                return false;
            }
            bool bRet = false;
            try
            {
                if (null == _sqlceConn)
                {
                    InitSqlCEConnection();
                }
                string sql = "select count(*) from t_Locate where locID=@locID";
                SqlCeParameter p1 = new SqlCeParameter("@locID", SqlDbType.NVarChar, 20);
                p1.Value = locID;
                object objRet = SqlCeHelper.ExecuteScalar(_sqlceConn, sql, p1);
                if (null != objRet && Convert.ToInt32(objRet) > 0)
                {
                    bRet = true;
                }
                else
                {
                    Common.PlayWarning();
                    bRet = false;
                }
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex);
                MessageBox.Show(ex.Message);
            }
            return bRet;
        }
        
        /// <summary>
        /// 单别验证
        /// </summary>
        /// <param name="billCode"></param>
        /// <returns></returns>
        protected virtual bool BillCodeVaild(string billCode)
        {
            if (string.IsNullOrEmpty(billCode))
            {
                return false;
            }
            bool bRet = false;
            try
            {
                if (null == _sqlceConn)
                {
                    InitSqlCEConnection();
                }
                string sql = "select count(*) from t_BillCode where billCode=@billCode";
                SqlCeParameter p1 = new SqlCeParameter("@billCode", SqlDbType.NVarChar, 20);
                p1.Value = billCode;
                object objRet = SqlCeHelper.ExecuteScalar(_sqlceConn, sql, p1);
                if (null != objRet && Convert.ToInt32(objRet) > 0)
                {
                    bRet = true;
                }
                else
                {
                    Common.PlayWarning();
                    bRet = false;
                }
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex);
                MessageBox.Show(ex.Message);
            }
            return bRet;
        }

        /// <summary>
        /// 其他类型验证
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected virtual bool DataVaild(object obj)
        {
            return false;
        }

        /// <summary>
        /// 版本检测
        /// </summary>
        protected virtual void HasNewVersion()
        {

            HasNewVersion(Assembly.GetCallingAssembly());
            
        }

        /// <summary>
        /// 版本检测
        /// </summary>
        /// <param name="assembly">程序集</param>
        /// <returns></returns>
        protected virtual void HasNewVersion(Assembly assembly)
        {
            /**********************************************************
                                 检测更新规则
             * 如果第一次打开对应模块,则进行一次版本检测
             * 此后每打开一次则检测次数+1,但不进行版本检测
             * 当检测次数大于10则进行该模块版本检测,并把检测次数置零
            ***********************************************************/
            if (_myAppID != AppID.Unknow)
            {
                if (_hasUpdateChecked.ContainsKey(_myAppID))
                {
                    ++_hasUpdateChecked[_myAppID];                    
                                      
                }
                else
                {
                    _hasUpdateChecked.Add(_myAppID, 0);
                }
                if (_hasUpdateChecked[_myAppID] % _maxCheckCount == 0)                   
                {
                    // 版本检测
                    string verInfo;
                    int nRet = Common.CheckUpdata(assembly, _myAppID, out verInfo);
                    if (nRet > 0)
                    {
                        string[] infoArr = verInfo.Split(';');
                        string desc = string.Empty;
                        string updataUrl = string.Empty;
                        if (infoArr.Length > 3)
                        {
                            updataUrl = infoArr[3];
                        }
                       
                        if (infoArr.Length > 4)
                        {
                            desc =infoArr[4];
                        }
                        if (!string.IsNullOrEmpty(updataUrl))
                        {
                            if (2 == nRet || (1 == nRet && DialogResult.Yes == MessageBox.Show("有新版本发布,是否更新?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)))
                            {
                                //更新
                                string args = " /" + updataUrl + " /" + desc;
                                string fullPath = Path.Combine(Common.ApplicationPath, "update.exe");
                                Process pross = System.Diagnostics.Process.Start(fullPath, updataUrl); //启动更新程序
                                System.Diagnostics.Process.GetCurrentProcess().Kill();
                            }
                        }
                        
                    }
                    

                }
                string info = "模块ID:" + _myAppID.ToString() + ";\r\n模块信息:" + assembly.ToString() +"\r\n已打开次数:"+ _hasUpdateChecked[_myAppID].ToString();
                MessageBox.Show(info);
            }            
        }
    }
}